<template>
  <div class="pad-content-box form-no-padding-box con-box">
    <div class="sale-add">
      <div class="sale-title">应收账单</div>
      <div class="sale-title-right">
        <div class="add" @click="addSale">添加押金</div>
      </div>
    </div>
    <el-table class="has-tab-header-border new-table-style cost-box bold-scrollbar-table" :border="true" size="small" :data="tableData" align="center">
      <el-table-column label="序号" type="index" align="center" width="55"></el-table-column>
      <el-table-column label="客户" width="130">
        <template slot-scope="scope">
          <el-select v-if="scope.row.isSelf" class="no-border-input yj-input" v-model="scope.row.customerKeys" :disabled="tableData.length > 1 ? true : false" placeholder="请选择" @change="changeClient(scope.row.customerKeys, scope.row)">
            <el-option v-for="item in options.clientList" :key="item.primaryKey" :label="item.partnerName" :value="item.primaryKey" />
          </el-select>
          <span class="font-size-14" v-else>{{ scope.row.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同编号" width="130">
        <template slot-scope="scope">
          <el-select v-if="scope.row.isSelf" class="no-border-input yj-input" v-model="scope.row.contractCode" placeholder="请选择" @change="changeContract(scope.row)">
            <el-option v-for="item in contractList" :key="item.contractCode" :label="item.contractCode" :value="item.contractCode" />
          </el-select>
          <span class="font-size-14" v-else>{{ scope.row.contractCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资产" width="130">
        <template slot-scope="scope">
          <el-select v-if="scope.row.isSelf" class="no-border-input yj-input" v-model="scope.row.chargeItemCode" placeholder="请选择" @change="setAssetKey(scope.row)">
            <el-option v-for="item in scope.row.assetList" :key="item.assetCode" :label="item.assetName" :value="item.assetCode" />
          </el-select>
          <span class="font-size-14" v-else>{{ scope.row.assetCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="费项名称" width="150">
        <template slot-scope="scope">
          <el-select :disabled="!scope.row.isSelf ? true : false" class="no-border-input yj-input" v-model="scope.row.bizType" :placeholder="!scope.row.isSelf ? '' : '请选择'">
            <el-option v-for="item in options.chargeCashPledgeList" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应缴日期" min-width="150">
        <template slot-scope="scope">
          <el-date-picker class="no-border-input yj-input" v-model="scope.row.paymentDeadline" value-format="timestamp" type="date" :placeholder="!scope.row.isSelf ? '' : '请选择'" :disabled="!scope.row.isSelf ? true : false"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" label="计费开始日期" min-width="150">
        <template slot-scope="scope">
          <el-date-picker class="no-border-input yj-input" v-model="scope.row.cycleStartTime" value-format="timestamp" type="date" :placeholder="!scope.row.isSelf ? '' : '请选择'" :disabled="!scope.row.isSelf ? true : false"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" label="计费结束日期" min-width="150">
        <template slot-scope="scope">
          <el-date-picker class="no-border-input yj-input" v-model="scope.row.cycleEndTime" value-format="timestamp" type="date" :placeholder="!scope.row.isSelf ? '' : '请选择'" :disabled="!scope.row.isSelf ? true : false"></el-date-picker>
        </template>
      </el-table-column>

      <el-table-column align="center" label="总金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <el-input-number v-if="scope.row.isSelf" :min="0" :controls="false" class="no-border-input yj-input" v-model="scope.row.amountReceivable" @blur="triggerAmount(scope.row)" :placeholder="!scope.row.isSelf ? '' : '请输入'"></el-input-number>
          <span v-else>{{ scope.row.amountReceivable | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="未结金额" class-name="no-padding" min-width="120">
        <template slot-scope="scope">
          <el-input-number v-if="scope.row.isSelf" :min="0" :controls="false" class="no-border-input yj-input" v-model="scope.row.unPaymentAmount" @blur="triggerAmount(scope.row)" :placeholder="!scope.row.isSelf ? '' : '请输入'"></el-input-number>
          <span v-else>{{ scope.row.unPaymentAmount | moneyFilterNoUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本次收款金额" align="center" width="130">
        <template slot-scope="scope">
          <el-input-number :controls="false" :min="0" class="no-border-input yj-input" v-model="scope.row.paymentAmount" @blur="triggerAmount(scope.row)" placeholder="请输入"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="60">
        <template slot-scope="scope">
          <el-button type="text" @click="deleteSale(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="font-size-17 font-weight-700 padding-top-40 padding-bottom-20">收款信息</div>
    <form-common :filed-list="formList" ref="form" :formObj="formObj"></form-common>

    <div class="t-center">
      <el-button size="mini" @click="closeDialog" class="el-button-reset">取 消</el-button>
      <el-button size="mini" type="primary" @click="confirmFn">保 存</el-button>
    </div>
  </div>
</template>

<script>
  import formCommon from '@g/components/form/formCommon.vue';
  import { gatherAdjustList } from '../../../assets/form';
  import $ from 'jquery';
  import { requestTips } from '@/common/js/utils.js';
  import { apiDepositCollection } from '../../../api/depositManage';
  import { apiContractByClient, apiAssetList } from '../../../api/billManage';

  export default {
    name: 'bill',
    props: {
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
      checkList: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },

    data() {
      return {
        formObj: {},
        post: true,
        chargeList: [],
        tableData: [],
        formList: gatherAdjustList,
        userInfo: JSON.parse(localStorage.getItem('userInfo')),
        contractList: [],
      };
    },

    methods: {
      init() {
        this.tableData = [];
        this.tableData = this.checkList || [];
        this.initFormData();
        this.setSelectOptions();
        if (this.checkList.length > 0) {
          this.getContractList(this.tableData[0].customerKeys);
        }
      },

      //合同数据源根据客户
      async getContractList(customerKey, row) {
        if (row) {
          row.contractCode = '';
          row.assetCode = '';
        }
        let res = await apiContractByClient({
          partnerKey: customerKey,
        });
        this.contractList = res.rows || [];
      },

      //改变客户
      changeClient(customerKey, row) {
        this.formObj = this.$refs.form.returnModel();
        let target = this.options.clientList.find(item => customerKey == item.primaryKey);
        let clientName = target ? target.partnerName : '';
        this.$set(this.formObj, 'clientName', clientName);
        this.getContractList(customerKey, row);
      },

      //资产数据源根据合同
      async changeContract(row) {
        row.assetCode = '';
        let target = this.contractList.find(item => row.contractCode == item.contractCode);
        row.contractKey = target ? target.primaryKey : '';
        let res = await apiAssetList({ contractCode: row.contractCode, status: 2 });
        res.rows.forEach(item => {
          if (item.assetType) {
            row.assetList.push(item);
          }
        });
      },

      initFormData() {
        this.$set(this.formObj, 'chargeUserName', this.userInfo.nickname);
        if (this.checkList.length > 0 && !this.tableData[0].isSelf) {
          this.$set(this.formObj, 'clientName', this.tableData[0].customerName);
        }
      },

      //收款核销收款金额>=0才能提交
      async confirmFn() {
        if (this.tableData.length == 0) {
          this.$message.warning('账单为空！！');
          return;
        }

        let model = this.$refs.form.validateForm(); //基本信息
        if (!model) return;

        let validateMustCost = this.validateMustCost();
        if (!validateMustCost) {
          this.$message.warning('请检查必填项！');
          return;
        }
        model.billList = this.tableData;
        let res = await apiDepositCollection(model);
        requestTips(res, () => {
          this.dialogShow = false;
          this.$emit('refresh');
        });
      },

      //设置setAssetKey
      setAssetKey(row) {
        let target = row.assetList.find(item => row.chargeItemCode == item.assetCode);
        row.bizId = target ? target.assetKey : '';
        row.chargeItemName = target ? target.assetName : '';
      },

      addSale() {
        let customerKeys = '';
        if (this.tableData.length > 0) {
          customerKeys = this.tableData[0].customerKeys;
        }
        this.tableData.push({
          isSelf: true,
          assetList: [],
          customerKeys: customerKeys || '',
          assetCode: '',
        });
      },

      deleteSale(index) {
        this.tableData.splice(index, 1);
      },

      closeDialog(data) {
        this.$emit('closeDialog', data);
      },

      //赋值下拉框数据源
      setSelectOptions() {
        this.formList.forEach(ele => {
          if (ele.bindFieldName == 'paymentMethod') {
            ele.optionList = this.options.paymentMethodList || [];
          }
        });
      },

      //校验 计算收款金额
      triggerAmount(row) {
        if (row.amountReceivable < row.unPaymentAmount) {
          row.unPaymentAmount = 0;
        }
        if (row.unPaymentAmount < row.paymentAmount) {
          row.paymentAmount = 0;
        }
        this.formObj = this.$refs.form.returnModel();
        let price = this.getAllAmount();
        this.$set(this.formObj, 'receivedAmount', price);
      },

      //计算收款金额
      getAllAmount() {
        let num = this.tableData.reduce((prev, item) => {
          prev += item.paymentAmount || 0;
          return prev;
        }, 0);
        return num || 0;
      },

      //校验合同费用约定的必填
      validateMustCost() {
        for (let i = 0, len = $('.cost-box').find('.el-input__inner').length; i < len; i++) {
          let item = $('.cost-box').find('.el-input__inner')[i];
          if ($(item).val() == '') {
            $(item).css('border', '1px solid red');
            return false;
          } else {
            $(item).css('border', 'none');
          }
        }
        return true;
      },
    },

    components: { formCommon },
  };
</script>

<style lang="scss" scoped>
  .line-box {
    width: 1px;
    height: 80px;
    background: #d8d8d8;
  }
  ::v-deep .has-tab-header-border .el-tabs__header {
    border: none;
  }
  ::v-deep .has-tab-header-border .el-tabs__header {
    border: none;
  }
  .sale-add {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .sale-title {
      font-size: 16px;
      font-weight: bold;
      color: #666;
      height: 30px;
      line-height: 30px;
    }
    .sale-title-right {
      display: flex;
      justify-content: flex-start;
    }
    .add {
      background: #409eff;
      padding: 0 15px;
      color: #fff;
      height: 30px;
      line-height: 30px;
      border-radius: 3px;
      cursor: pointer;
    }
    .cancel {
      margin-left: 10px;
      background: #f56c6c;
      padding: 0 15px;
      color: #fff;
      height: 30px;
      line-height: 30px;
      border-radius: 3px;
    }
  }
  .bold-scrollbar-table {
    ::v-deep .el-input.is-disabled .el-input__inner {
      background: #fff;
      color: #333;
    }
  }
  .con-box {
    .new-table-style td .cell {
      font-size: 14px !important;
    }
    .new-table-style td .cell .el-button,
    .new-table-style td .cell span {
      font-size: 14px !important;
    }
  }
</style>
